#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright [新大陆集成服务一部-系统组].
# Create Date:
# Update Date:
__authors__ = "新大陆集成服务一部-系统组"

"""4A数据文件检查程序.
判断数据文件传输是否异常中断.

"""

import os
import time
import datetime
import sqlite3


class ChkData():
    def __init__(self):
        self.localdir = "/oracle/oracle/impdata"
        self.iplist = ["23", "24", "25", "26"]
        self.mark_mid = "_"
        self.completemark = "complete"
        self.puttingmark = "putting"
        self.filesuffix = "4Alog_" + datetime.datetime.strftime(datetime.datetime.today(), "%Y%m%d") + ".dmp"
        self.dbname = '4afilecheck.db'
        self.chkdb = os.path.join(self.localdir, self.dbname)

    def chk(self):
        try:
            print "#" * 120
            print "#" + "Check the 4ALog file".center(118) + "#"
            print "#" * 120
            if os.path.isfile(self.chkdb):
                pass
            else:
                os.system('''sqlite3 ''' + self.chkdb + ''' <<EOF
    .quit
    EOF''')
            db = sqlite3.connect(self.chkdb)
            cur = db.cursor()
            for ip in self.iplist:
                print " "
                print "+" * 5 + str(datetime.datetime.now())
                print " " * 5 + "ip:" + ip
                completefile = os.path.join(self.localdir, self.completemark + self.mark_mid + ip)
                puttingfile = os.path.join(self.localdir, self.puttingmark + self.mark_mid + ip)
                if not os.path.isfile(completefile) and os.path.isfile(puttingfile):
                    localfile = os.path.join(self.localdir, ip + "_" + self.filesuffix)
                    cur.execute("insert into chk(ctime,file,size) values(:1,:2,:3)",
                                (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), ip, os.stat(localfile).st_size))
                    cur.execute(
                        "select coalesce(max(size),0),coalesce(min(size),0),count(*) from (select * from chk where file=:1 and ctime between :2 and :3 order by ctime desc limit 2)",
                        (ip, datetime.date.today(), datetime.date.today() + datetime.timedelta(days=1),))
                    ret = cur.fetchone()
                    if ret[2] > 1:
                        print ret[0], ret[1]
                        if ret[0] == ret[1]:
                            os.remove(puttingfile)
                    db.commit()
        except Exception, e:
            print e
        finally:
            print " "
            print "#" * 120
            print "#" + "Finally".center(118) + "#"
            print "#" * 120
            cur.close()
            db.commit()
            db.close()


if __name__ == "__main__":
    do = ChkData()
    do.chk()
